<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ApiEnum } from '@/enum/ApiEnum'
import { IEditorConfig, IDomEditor, IToolbarConfig } from '@wangeditor/editor'
interface Props {
  modelValue?: string,
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
})

const emit = defineEmits(['update:modelValue'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<IDomEditor>()

// 内容 HTML
const valueHtml = ref(props.modelValue)

type InsertFnType = (url: string) => void
const editorConfig:Partial<IEditorConfig> = {
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 5 * 1024 * 1024, // 1M
      server: ApiEnum.UPLOAD_IMAGE_URL, //后端的上传文件的地址
      // server: "http://localhost:8001/api/upload/image",
      // 后端接收的文件名称
      fieldName: "file",
       // 自定义插入
    async customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
    
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        insertFn(res?.data?.url)
    }
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

watch([valueHtml], (value: any) => {
  emit('update:modelValue', editorRef.value?.getHtml())
})



//创建工具栏
const mode = ref('default')

const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: ['group-video', 'undo', 'redo'],
}



</script>
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      style="height: 250px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      
       />
  </div>
</template>